#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
增强版Web服务 - 集成真实航班数据
"""
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
import json
from datetime import datetime, timedelta
import openai
import os
import sys

# 添加crawler_lab路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'crawler_lab'))

app = Flask(__name__)
CORS(app)

# API配置
DEEPSEEK_API_KEY = "sk-00d9e28b0be74eb4b070a062b7cb73b7"
DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1"
DEEPSEEK_MODEL = "deepseek-chat"
GAODE_API_KEY = "003df4ac18f1cca97eaf59dc90afbaa2"

class EnhancedTravelAPI:
    def __init__(self):
        self.gaode_key = GAODE_API_KEY
        self.base_url = "https://restapi.amap.com/v3"
        self.flight_data = []
        
        # 初始化DeepSeek AI客户端
        try:
            if hasattr(openai, 'OpenAI'):
                self.ai_client = openai.OpenAI(
                    api_key=DEEPSEEK_API_KEY,
                    base_url=DEEPSEEK_BASE_URL
                )
                self.ai_available = True
                self.use_new_client = True
                print("✅ DeepSeek AI 客户端初始化成功")
            else:
                openai.api_key = DEEPSEEK_API_KEY
                openai.api_base = DEEPSEEK_BASE_URL
                self.ai_available = True
                self.use_new_client = False
                print("✅ DeepSeek AI 客户端初始化成功 (旧版本)")
        except Exception as e:
            print(f"❌ DeepSeek AI 客户端初始化失败: {e}")
            self.ai_available = False
        
        # 加载航班数据
        self.load_flight_data()
    
    def load_flight_data(self):
        """加载航班数据"""
        try:
            # 尝试从JSON文件加载
            json_path = os.path.join(os.path.dirname(__file__), '..', 'crawler_lab', 'flight_data.json')
            if os.path.exists(json_path):
                with open(json_path, 'r', encoding='utf-8') as f:
                    self.flight_data = json.load(f)
                print(f"✅ 加载了 {len(self.flight_data)} 条航班数据")
            else:
                print("⚠️ 未找到航班数据文件，将使用模拟数据")
                self.flight_data = self.generate_mock_flight_data()
        except Exception as e:
            print(f"❌ 加载航班数据失败: {e}")
            self.flight_data = self.generate_mock_flight_data()
    
    def generate_mock_flight_data(self):
        """生成模拟航班数据"""
        mock_data = [
            {
                'flight_number': 'CA1234',
                'airline': '中国国航',
                'origin': '大连',
                'destination': '北京',
                'dep_time': '2025-09-19 08:00',
                'arr_time': '2025-09-19 10:30',
                'price': 350,
                'dep_airport': '大连机场',
                'arr_airport': '北京首都机场',
                'aircraft': '波音737-800',
                'has_stop': '否',
                'is_transfer': '否',
                'source': '模拟数据'
            },
            {
                'flight_number': 'MU5678',
                'airline': '东方航空',
                'origin': '大连',
                'destination': '北京',
                'dep_time': '2025-09-19 14:30',
                'arr_time': '2025-09-19 17:00',
                'price': 420,
                'dep_airport': '大连机场',
                'arr_airport': '北京首都机场',
                'aircraft': '空客A320',
                'has_stop': '否',
                'is_transfer': '否',
                'source': '模拟数据'
            }
        ]
        return mock_data
    
    def geocode(self, address):
        """地理编码"""
        url = f"{self.base_url}/geocode/geo"
        params = {
            'key': self.gaode_key,
            'address': address,
            'output': 'json'
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('status') == '1' and data.get('geocodes'):
                    geocode = data['geocodes'][0]
                    location = geocode.get('location', '').split(',')
                    if len(location) == 2:
                        return {
                            'success': True,
                            'location': {
                                'lng': float(location[0]),
                                'lat': float(location[1])
                            },
                            'formatted_address': geocode.get('formatted_address', ''),
                            'city': geocode.get('city', ''),
                        }
            return {'success': False, 'error': f'无法解析地址: {address}'}
        except Exception as e:
            return {'success': False, 'error': f'地理编码异常: {str(e)}'}
    
    def get_weather(self, city):
        """获取天气信息"""
        url = f"{self.base_url}/weather/weatherInfo"
        params = {
            'key': self.gaode_key,
            'city': city,
            'output': 'json'
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('status') == '1' and data.get('lives'):
                    weather = data['lives'][0]
                    return {
                        'success': True,
                        'weather': {
                            'city': weather.get('city', ''),
                            'weather': weather.get('weather', ''),
                            'temperature': weather.get('temperature', ''),
                            'humidity': weather.get('humidity', ''),
                            'wind_power': weather.get('windpower', ''),
                            'wind_direction': weather.get('winddirection', ''),
                        }
                    }
            return {'success': False, 'error': '天气信息获取失败'}
        except Exception as e:
            return {'success': False, 'error': f'天气查询异常: {str(e)}'}
    
    def get_ai_response(self, message):
        """获取AI回复"""
        if not self.ai_available:
            return self.get_fallback_response(message)
        
        try:
            system_prompt = """你是一个专业的旅行规划AI助手，专门帮助用户规划出行路线。你的主要功能包括：

1. 路线规划：根据用户提供的出发地和目的地，推荐最佳的出行方案（高铁、飞机、汽车等）
2. 天气查询：提供目的地的天气信息
3. 地点搜索：帮助用户搜索感兴趣的地点
4. 出行建议：根据用户需求提供个性化的出行建议

请用友好、专业的语气回复用户，并提供实用的建议。"""
            
            if self.use_new_client:
                response = self.ai_client.chat.completions.create(
                    model=DEEPSEEK_MODEL,
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": message}
                    ],
                    max_tokens=1000,
                    temperature=0.7
                )
                return response.choices[0].message.content
            else:
                response = openai.ChatCompletion.create(
                    model=DEEPSEEK_MODEL,
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": message}
                    ],
                    max_tokens=1000,
                    temperature=0.7
                )
                return response.choices[0].message.content
        except Exception as e:
            print(f"DeepSeek AI调用失败: {e}")
            return self.get_fallback_response(message)
    
    def get_fallback_response(self, message):
        """备用回复"""
        if '路线' in message or '到' in message:
            return "🚀 我可以帮您规划出行路线！\n\n请使用上方的搜索框输入：\n• 出发地：如'大连'或'大连交通大学'\n• 目的地：如'北京'或'北京首都机场'\n\n然后点击'搜索路线'按钮，我会为您提供多种出行方案！"
        elif '天气' in message:
            return "🌤️ 我可以帮您查询天气信息！\n\n请告诉我您想查询哪个城市的天气，比如：\n• 查询北京天气\n• 查询上海天气\n• 查询大连天气"
        else:
            return "👋 您好！我是您的出行助手！\n\n我可以帮您：\n• 🚄 规划出行路线\n• 🌤️ 查询天气信息\n• 🔍 搜索地点信息\n• 🗺️ 显示地图路线\n\n请告诉我您需要什么帮助！"
    
    def search_flights(self, origin, destination, date=None):
        """搜索航班"""
        if not date:
            date = datetime.now().strftime('%Y-%m-%d')
        
        # 从航班数据中筛选
        matching_flights = []
        for flight in self.flight_data:
            if (flight['origin'] == origin and flight['destination'] == destination):
                matching_flights.append(flight)
        
        # 如果没有找到匹配的航班，生成一些模拟数据
        if not matching_flights:
            matching_flights = self.generate_route_data(origin, destination, date)
        
        return matching_flights
    
    def generate_route_data(self, origin, destination, date):
        """生成路线数据"""
        routes = []
        
        # 航班路线
        if origin == "大连" and destination == "北京":
            routes.extend([
                {
                    'type': 'flight',
                    'flight_number': 'CA1234',
                    'airline': '中国国航',
                    'origin': origin,
                    'destination': destination,
                    'departure_time': f"{date} 08:00",
                    'arrival_time': f"{date} 10:30",
                    'price': 350,
                    'duration': '2小时30分',
                    'description': '飞机直达，快速舒适'
                },
                {
                    'type': 'flight',
                    'flight_number': 'MU5678',
                    'airline': '东方航空',
                    'origin': origin,
                    'destination': destination,
                    'departure_time': f"{date} 14:30",
                    'arrival_time': f"{date} 17:00",
                    'price': 420,
                    'duration': '2小时30分',
                    'description': '飞机直达，时间合适'
                }
            ])
        
        # 高铁路线
        routes.extend([
            {
                'type': 'high_speed_rail',
                'train_number': 'G1234',
                'origin': origin,
                'destination': destination,
                'departure_time': f"{date} 08:30",
                'arrival_time': f"{date} 12:00",
                'price': 150,
                'duration': '3小时30分',
                'description': '高铁直达，经济实惠'
            },
            {
                'type': 'high_speed_rail',
                'train_number': 'G5678',
                'origin': origin,
                'destination': destination,
                'departure_time': f"{date} 15:00",
                'arrival_time': f"{date} 18:30",
                'price': 180,
                'duration': '3小时30分',
                'description': '高铁直达，舒适便捷'
            }
        ])
        
        return routes
    
    def generate_routes(self, origin, destination, date=None):
        """生成路线方案"""
        if not date:
            date = datetime.now().strftime('%Y-%m-%d')
        
        # 获取航班数据
        flights = self.search_flights(origin, destination, date)
        
        # 生成路线
        routes = []
        
        # 处理航班数据
        for flight in flights:
            if 'flight_number' in flight:
                route = {
                    'total_time': 2.5,
                    'total_price': flight['price'],
                    'transfers': 0,
                    'details': [{
                        'type': 'flight',
                        'origin': flight['origin'],
                        'destination': flight['destination'],
                        'departure_time': flight['dep_time'],
                        'arrival_time': flight['arr_time'],
                        'price': flight['price'],
                        'flight_number': flight['flight_number'],
                        'airline': flight['airline'],
                        'aircraft': flight.get('aircraft', ''),
                        'can_buy': True,
                        'description': f"{flight['airline']} {flight['flight_number']} - {flight.get('aircraft', '')}"
                    }]
                }
                routes.append(route)
        
        # 添加高铁路线
        routes.extend([
            {
                'total_time': 3.5,
                'total_price': 150,
                'transfers': 0,
                'details': [{
                    'type': 'high_speed_rail',
                    'origin': origin,
                    'destination': destination,
                    'departure_time': f"{date} 08:30",
                    'arrival_time': f"{date} 12:00",
                    'price': 150,
                    'train_number': 'G1234',
                    'can_buy': True,
                    'description': '高铁直达，经济实惠'
                }]
            },
            {
                'total_time': 4.0,
                'total_price': 120,
                'transfers': 1,
                'details': [
                    {
                        'type': 'high_speed_rail',
                        'origin': origin,
                        'destination': '沈阳',
                        'departure_time': f"{date} 08:00",
                        'arrival_time': f"{date} 10:00",
                        'price': 80,
                        'train_number': 'G1235',
                        'can_buy': True,
                        'description': '第一段：高铁'
                    },
                    {
                        'type': 'high_speed_rail',
                        'origin': '沈阳',
                        'destination': destination,
                        'departure_time': f"{date} 10:30",
                        'arrival_time': f"{date} 12:00",
                        'price': 40,
                        'train_number': 'G1236',
                        'can_buy': True,
                        'description': '第二段：高铁'
                    }
                ]
            }
        ])
        
        return routes

# 初始化API实例
travel_api = EnhancedTravelAPI()

@app.route('/api/test', methods=['GET'])
def test():
    return jsonify({
        'success': True,
        'message': 'Enhanced Travel API服务运行正常',
        'flight_data_count': len(travel_api.flight_data),
        'timestamp': datetime.now().isoformat()
    })

@app.route('/api/status', methods=['GET'])
def status():
    return jsonify({
        'success': True,
        'status': 'online',
        'version': '2.0.0',
        'apis': {
            'gaode': 'available',
            'ai': 'available' if travel_api.ai_available else 'unavailable',
            'flight_data': f'{len(travel_api.flight_data)} 条航班数据'
        },
        'timestamp': datetime.now().isoformat()
    })

@app.route('/api/cities', methods=['GET'])
def get_cities():
    """获取城市列表"""
    cities_list = [
        {'id': 1, 'name': '北京', 'code': 'BJP', 'level': 'province'},
        {'id': 2, 'name': '上海', 'code': 'SHH', 'level': 'province'},
        {'id': 3, 'name': '广州', 'code': 'GZQ', 'level': 'province'},
        {'id': 4, 'name': '深圳', 'code': 'SZQ', 'level': 'province'},
        {'id': 5, 'name': '杭州', 'code': 'HZH', 'level': 'province'},
        {'id': 6, 'name': '南京', 'code': 'NJH', 'level': 'province'},
        {'id': 7, 'name': '武汉', 'code': 'WHN', 'level': 'province'},
        {'id': 8, 'name': '成都', 'code': 'CDW', 'level': 'province'},
        {'id': 9, 'name': '西安', 'code': 'XAY', 'level': 'province'},
        {'id': 10, 'name': '重庆', 'code': 'CQW', 'level': 'province'},
        {'id': 11, 'name': '天津', 'code': 'TJP', 'level': 'province'},
        {'id': 12, 'name': '青岛', 'code': 'QDK', 'level': 'province'},
        {'id': 13, 'name': '大连', 'code': 'DLT', 'level': 'province'},
        {'id': 14, 'name': '合肥', 'code': 'HFH', 'level': 'province'},
        {'id': 42, 'name': '大连交通大学', 'code': 'DLT', 'level': 'university'},
        {'id': 43, 'name': '合肥南站', 'code': 'ENH', 'level': 'station'},
    ]
    
    return jsonify({
        'success': True,
        'cities': cities_list,
        'source': f'城市数据库（包含{len(cities_list)}个城市）',
        'total': len(cities_list)
    })

@app.route('/api/search', methods=['POST'])
def search():
    """路线搜索"""
    data = request.get_json()
    origin = data.get('origin', '')
    destination = data.get('destination', '')
    date = data.get('departure_date', '')
    
    if not origin or not destination:
        return jsonify({
            'success': False,
            'error': '请提供出发地和目的地'
        })
    
    print(f"正在搜索: {origin} -> {destination}")
    
    # 地理编码
    origin_geocode = travel_api.geocode(origin)
    destination_geocode = travel_api.geocode(destination)
    
    print(f"出发地编码结果: {origin_geocode}")
    print(f"目的地编码结果: {destination_geocode}")
    
    # 生成路线
    routes = travel_api.generate_routes(origin, destination, date)
    
    return jsonify({
        'success': True,
        'routes': routes,
        'message': f'为您找到 {len(routes)} 条路线',
        'origin_info': origin_geocode,
        'destination_info': destination_geocode,
        'flight_data_used': len(travel_api.flight_data)
    })

@app.route('/api/flights', methods=['POST'])
def get_flights():
    """获取航班数据"""
    data = request.get_json()
    origin = data.get('origin', '')
    destination = data.get('destination', '')
    date = data.get('date', '')
    
    if not origin or not destination:
        return jsonify({
            'success': False,
            'error': '请提供出发地和目的地'
        })
    
    flights = travel_api.search_flights(origin, destination, date)
    
    return jsonify({
        'success': True,
        'flights': flights,
        'message': f'找到 {len(flights)} 个航班',
        'total_data': len(travel_api.flight_data)
    })

@app.route('/api/chat', methods=['POST'])
def chat():
    """AI聊天接口"""
    data = request.get_json()
    message = data.get('message', '')
    
    if not message:
        return jsonify({
            'success': False,
            'error': '请提供消息内容'
        })
    
    # 获取AI回复
    response = travel_api.get_ai_response(message)
    
    # 生成建议
    suggestions = []
    if '路线' in message or '到' in message:
        suggestions = ['从北京到上海', '从广州到深圳', '从杭州到南京']
    elif '天气' in message:
        suggestions = ['查询北京天气', '查询上海天气', '查询广州天气']
    else:
        suggestions = ['查询天气', '规划路线', '搜索地点']
    
    return jsonify({
        'success': True,
        'response': response,
        'suggestions': suggestions,
        'ai_model': 'DeepSeek Chat' if travel_api.ai_available else '智能AI助手'
    })

@app.route('/api/weather', methods=['GET', 'POST'])
def weather():
    """天气查询接口"""
    if request.method == 'GET':
        city = request.args.get('city', '')
    else:
        data = request.get_json()
        city = data.get('city', '')
    
    if not city:
        return jsonify({
            'success': False,
            'error': '请提供城市名称'
        })
    
    result = travel_api.get_weather(city)
    return jsonify(result)

if __name__ == '__main__':
    print("🚀 启动增强版Travel API服务...")
    print("📍 高德地图API: 已配置")
    print("🤖 DeepSeek AI: 已配置" if travel_api.ai_available else "🤖 DeepSeek AI: 未配置")
    print(f"✈️ 航班数据: {len(travel_api.flight_data)} 条")
    print("🌐 服务地址: http://localhost:5000")
    print("📋 API文档: http://localhost:5000/api/status")
    app.run(debug=True, host='0.0.0.0', port=5000)